package tss.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;


public class HBaseDriver {

    private Configuration config;

    public HBaseDriver() {
        this("localhost");
    }
    
    public HBaseDriver(String zooKeeperAddress) {
        this.config = HBaseConfiguration.create();
        config.set("hbase.zookeeper.quorum", "localhost");
    }

    public Configuration getConfiguration() {
        return config;
    }

    public void doWithAdminConnection(HBaseAdminAction action) {
        try (HBaseAdmin hBaseAdmin = new HBaseAdmin(config)) {            
            action.perform(hBaseAdmin);
        } catch (MasterNotRunningException e) {
            throw new RuntimeException(e);
        } catch (ZooKeeperConnectionException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }        
    }

    public void doWithTable(String tableName, HBaseTableAction action) {
        try (HTable hTable = new HTable(config, tableName)) {
            action.perform(hTable);            
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
    }

    public <T> T queryTable(String tableName, HBaseTableQuery<T> query) {
        try (HTable hTable = new HTable(config, tableName)) {
            return query.perform(hTable);            
        } catch (IOException e) {
            throw new RuntimeException(e);
        }         
    }
}
